/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.core.be;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.inspur.edp.bef.api.BefRtBeanUtil;
import com.inspur.edp.bef.api.action.assembler.IMgrActionAssemblerFactory;
import com.inspur.edp.bef.api.be.BEInfo;
import com.inspur.edp.bef.api.be.IBEContext;
import com.inspur.edp.bef.api.be.IBEManager;
import com.inspur.edp.bef.api.be.IBusinessEntity;
import com.inspur.edp.bef.api.exceptions.BefEngineException;
import com.inspur.edp.bef.api.exceptions.ErrorCodes;
import com.inspur.edp.bef.api.lcp.BefTempTableContext;
import com.inspur.edp.bef.api.lcp.ResponseContext;
import com.inspur.edp.bef.api.lcp.StandardLcpParam;
import com.inspur.edp.bef.api.parameter.clone.CloneParameter;
import com.inspur.edp.bef.api.parameter.retrieve.RespectiveRetrieveResult;
import com.inspur.edp.bef.api.parameter.retrieve.RetrieveChildResult;
import com.inspur.edp.bef.api.parameter.retrieve.RetrieveParam;
import com.inspur.edp.bef.api.parameter.retrieve.RetrieveResult;
import com.inspur.edp.bef.core.action.base.BEMgrActionExecutor;
import com.inspur.edp.bef.core.action.base.ManagerActionFactory;
import com.inspur.edp.bef.core.action.clear.AutoClearBufferMgrAction;
import com.inspur.edp.bef.core.action.clear.ClearBufferMgrAction;
import com.inspur.edp.bef.core.action.clear.ClearChangesetMgrAction;
import com.inspur.edp.bef.core.action.clear.ClearLockMgrAction;
import com.inspur.edp.bef.core.action.delete.DeleteChildMgrAction;
import com.inspur.edp.bef.core.action.delete.DeleteMgrAction;
import com.inspur.edp.bef.core.action.delete.MultiDeleteMgrAction;
import com.inspur.edp.bef.core.action.modify.FullModifyMgrAction;
import com.inspur.edp.bef.core.action.modify.ModifyByFilterMgrAction;
import com.inspur.edp.bef.core.action.modify.ModifyMgrAction;
import com.inspur.edp.bef.core.action.modify.MultiModifyMgrAction;
import com.inspur.edp.bef.core.action.query.HasChangeDetailMgrAction;
import com.inspur.edp.bef.core.action.query.QueryManagerAction;
import com.inspur.edp.bef.core.action.query.QueryWithBufferMgrAction;
import com.inspur.edp.bef.core.action.query.QueryWithoutAuthInfoMgrAction;
import com.inspur.edp.bef.core.action.retrieve.EditManagerAction;
import com.inspur.edp.bef.core.action.retrieve.IsEffectiveMgrAction;
import com.inspur.edp.bef.core.action.retrieve.MultiEffectiveMgrAction;
import com.inspur.edp.bef.core.action.retrieve.MultiEffectiveMgrAction.MultiEffectiveResult;
import com.inspur.edp.bef.core.action.retrieve.MultiRetrieveMgrAction;
import com.inspur.edp.bef.core.action.retrieve.RetrieveChidAndChildMgrAction;
import com.inspur.edp.bef.core.action.retrieve.RetrieveChildMgrAction;
import com.inspur.edp.bef.core.action.retrieve.RetrieveManagerAction;
import com.inspur.edp.bef.core.action.retrievedefault.*;
import com.inspur.edp.bef.core.action.save.SaveContext;
import com.inspur.edp.bef.core.action.save.saveEvent.SaveEventBroker;
import com.inspur.edp.bef.core.action.tcc.MgrTccCancelAction;
import com.inspur.edp.bef.core.action.tcc.MgrTccConfirmAction;
import com.inspur.edp.bef.core.action.temptable.CreateTempTableMgrAction;
import com.inspur.edp.bef.core.action.temptable.DropTempTableMgrAction;
import com.inspur.edp.bef.core.action.variable.VariableModifyMgrAction;
import com.inspur.edp.bef.core.determination.builtinimpls.BefB4QueryDtmAssembler;
import com.inspur.edp.bef.core.determination.builtinimpls.BefBeforeRetrieveDtmAssembler;
import com.inspur.edp.bef.core.lock.LockService;
import com.inspur.edp.bef.core.session.BEFuncSessionBase;
import com.inspur.edp.bef.core.session.FuncSession;
import com.inspur.edp.bef.core.tcc.BefTccParamItem;
import com.inspur.edp.bef.spi.action.AbstractManagerAction;
import com.inspur.edp.bef.spi.action.assembler.mgrAssemblerFactory.MgrActionAssemblerFactory;
import com.inspur.edp.bef.spi.entity.AbstractBizEntityDeSerializer;
import com.inspur.edp.bef.spi.entity.AbstractBizEntitySerializer;
import com.inspur.edp.bef.spi.entity.builtinimpls.BefEntityResInfoImpl;
import com.inspur.edp.bef.spi.entity.builtinimpls.BefModelResInfoImpl;
import com.inspur.edp.bef.spi.entity.columnconfig.ColumnGenerateConfigLoader;
import com.inspur.edp.bef.spi.entity.columnconfig.ColumnGenerateInfo;
import com.inspur.edp.bef.spi.event.queryactionevent.BefQueryEventBroker;
import com.inspur.edp.bef.spi.event.retrievedefault.BefRetrieveDefaultBroker;
import com.inspur.edp.bef.spi.extend.IBEEntityExtend;
import com.inspur.edp.bef.spi.extend.IBEManagerExtend;
import com.inspur.edp.caf.transaction.api.annoation.tcc.BusinessActionContext;
import com.inspur.edp.cef.api.RefObject;
import com.inspur.edp.cef.api.action.EditResult;
import com.inspur.edp.cef.api.changeset.IChangesetManager;
import com.inspur.edp.cef.api.dataType.entity.ICefEntityContext;
import com.inspur.edp.cef.api.dataType.entity.ICefRootEntity;
import com.inspur.edp.cef.api.manager.IBufferManager;
import com.inspur.edp.cef.api.manager.ICefManagerContext;
import com.inspur.edp.cef.api.manager.IRepositoryFactory;
import com.inspur.edp.cef.api.manager.action.ICefMgrAction;
import com.inspur.edp.cef.api.manager.serialize.CefSerializeContext;
import com.inspur.edp.cef.api.repository.IRootRepository;
import com.inspur.edp.cef.api.resourceInfo.ModelResourceInfos;
import com.inspur.edp.cef.api.rootManager.IRootEntityCacheManager;
import com.inspur.edp.cef.api.rootManager.IRootManagerContext;
import com.inspur.edp.cef.core.rootmanager.CefRootManager;
import com.inspur.edp.cef.entity.UQConstraintConfig;
import com.inspur.edp.cef.entity.accessor.base.IAccessor;
import com.inspur.edp.cef.entity.changeset.AddChangeDetail;
import com.inspur.edp.cef.entity.changeset.ChangeType;
import com.inspur.edp.cef.entity.changeset.IChangeDetail;
import com.inspur.edp.cef.entity.changeset.ModifyChangeDetail;
import com.inspur.edp.cef.entity.condition.EntityFilter;
import com.inspur.edp.cef.entity.dependenceTemp.DataValidator;
import com.inspur.edp.cef.entity.entity.ICefData;
import com.inspur.edp.cef.entity.entity.IEntityData;
import com.inspur.edp.cef.entity.repository.DataSaveParameter;
import com.inspur.edp.cef.entity.repository.DataSaveResult;
import com.inspur.edp.cef.spi.determination.IEntityRTDtmAssembler;
import com.inspur.edp.cef.spi.entity.resourceInfo.EntityResInfo;
import com.inspur.edp.cef.spi.entity.resourceInfo.ModelResInfo;
import com.inspur.edp.cef.spi.jsonser.abstractcefchange.AbstractCefChangeJsonDeserializer;
import com.inspur.edp.cef.spi.jsonser.abstractcefchange.AbstractCefChangeSerializer;
import com.inspur.edp.cef.spi.jsonser.util.SerializerUtil;
import com.inspur.edp.cef.variable.api.data.IVariableData;
import com.inspur.edp.cef.variable.api.manager.IVariableManager;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 BEManager

*/
public abstract class BEManager extends CefRootManager implements IBEManager
{

	private StandardLcpParam lcpParam;
	//region Constructor

	protected BEManager()
	{
	}


		//endregion Constructor

		//region 属性
	public BEManagerContext getBEManagerContext() {return (BEManagerContext)getRootContext();}

	@Override
	public ICefManagerContext getContext() {return getBEManagerContext();}

	@Override
	public IEntityData createDataType() {return createObjectData();}
	@Override
	public IEntityData createEntity(){return createObjectData();}
	/**
	 BEManager所属业务类型

	*/
	private String privateBEType;
	@Override
	public final String getBEType()
	{
		return privateBEType;
	}
	//TODO: java版本临时注释 没有internal 先用public
	/* internal */ public void setBEType(String value)
	{
		privateBEType = value;
	}

	/**
	 BEManager所属业务类型等信息

	*/
	private BEInfo privateBEInfo;
	@Override
	public final BEInfo getBEInfo()
	{
		return privateBEInfo;
	}
	/* internal */ public void setBEInfo(BEInfo value)
	{
		if(value!=null)
		{
			if(value.getRootEntityCode()==null||value.getRootEntityCode().equals(""))
			{
				ModelResInfo modelInfo=innerGetModelInfo();
				if(modelInfo!=null&&modelInfo.getRootNodeCode()!=null&&modelInfo.getRootNodeCode().equals("")==false)
					value.setRootEntityCode(modelInfo.getRootNodeCode());
			}
		}
		privateBEInfo = value;
	}

	protected ModelResInfo innerGetModelInfo()
  {return getModelInfo();
  }

	private ResponseContext privateResponseContext;
	public final ResponseContext getResponseContext()
	{
		return privateResponseContext;
	}
	public final void setResponseContext(ResponseContext value)
	{
		privateResponseContext = value;
	}

	public boolean hasErrorMessage() {
		ResponseContext ctx = getResponseContext();
		if (ctx == null) {
			return false;
		}
		return ctx.hasErrorMessage();
	}

		//endregion

	@Override
	public boolean save()
	{
		//保存权限检查
		//CheckSaveAuthorition();

		return Execute(getManagerActionFactory().getSaveManagerAction(getBEManagerContext()));
		//var managerAction = getManagerActionFactory().getSaveManagerAction(getBEManagerContext());
		//return managerAction.do();
	}

	@Override
	public final EditResult edit(String id) {
		ManagerActionFactory mgrActionFactory = getManagerActionFactory();
		EditManagerAction mgrAction = mgrActionFactory.getEditManagerAction(getBEManagerContext(), id);
		return Execute(mgrAction );
	}

	@Override
	public final RespectiveRetrieveResult retrieve(String id)
	{
		RetrieveParam tempVar = new RetrieveParam();
		return retrieve(id, tempVar);
	}

	/**
	 检索单个数据

	 @param id 数据ID
	 @param para 检索参数
	*/
	@Override
	public final RespectiveRetrieveResult retrieve(String id, RetrieveParam para)
	{
		////检索权限检查
		//CheckRetrieveAuthorition();
		ManagerActionFactory mgrActionFactory = getManagerActionFactory();
		RetrieveManagerAction retrieveManagerAction = mgrActionFactory.getRetrieveManagerAction(getBEManagerContext(), id, para);
		return Execute(retrieveManagerAction);
		//return retrieveManagerAction.do();
	}

	@Override
	public final RespectiveRetrieveResult retrieveChild(java.util.List<String> nodeCodes, java.util.List<String> hierachyIdList, RetrieveParam par)
	{
		////检索权限检查
		//CheckRetrieveAuthorition();

		ManagerActionFactory mgrActionFactory = getManagerActionFactory();
		RetrieveChildMgrAction action = mgrActionFactory.getRetrieveChildManagerAction(getBEManagerContext(), nodeCodes, hierachyIdList, par);
		return Execute(action);
		//return retrieveManagerAction.do();
	}
	public final RetrieveChildResult retrieveChild(java.util.List<String> nodeCodes, java.util.List<String> hierachyIdList, ArrayList<String> ids,RetrieveParam par)
	{
		////检索权限检查
		//CheckRetrieveAuthorition();

		ManagerActionFactory mgrActionFactory = getManagerActionFactory();
		RetrieveChidAndChildMgrAction action = mgrActionFactory.getRetrieveChildAndChildManagerAction(getBEManagerContext(), nodeCodes, hierachyIdList,ids, par);
		return Execute(action);
		//return retrieveManagerAction.do();
	}

	@Override
	public final RetrieveResult retrieve(List<String> idList) {
		return retrieve(idList, new RetrieveParam());
	}

	/**
	 检索批量数据

	 @param idList 数据IDList
	 @param para 检索参数
	*/
	@Override
	public final RetrieveResult retrieve(List<String> idList, RetrieveParam para) {
		ManagerActionFactory mgrActionFactory = getManagerActionFactory();
		MultiRetrieveMgrAction multiRetrieveMgrAction = mgrActionFactory.getMultiRetrieveMgrAction(getBEManagerContext(), idList, para);
		return Execute(multiRetrieveMgrAction);
	}

	/**
	 根据变更集修改

	 @param changeDetail 变更集
	 @return
	*/
	@Override
	public final void modify(IChangeDetail changeDetail)
	{
		////修改权限检查
		//CheckModifyAuthorition();
		ManagerActionFactory mgrActionFactory = getManagerActionFactory();
		ModifyMgrAction modifyMgrAction = mgrActionFactory.getModifyMgrAction(getBEManagerContext(), changeDetail);
		Execute(modifyMgrAction);
	}

	/**
	 根据变更集列表批量修改

	 @param changeDetailList 变更集列表
	 @return
	*/
	@Override
	public final void modify(java.util.ArrayList<IChangeDetail> changeDetailList)
	{
		////修改权限检查
		//CheckModifyAuthorition();
		ManagerActionFactory mgrActionFactory = getManagerActionFactory();
		MultiModifyMgrAction multiModifyMgrAction = mgrActionFactory.getMultiModifyMgrAction(getBEManagerContext(), changeDetailList);
		Execute(multiModifyMgrAction);
	}

	@Override
	public final void modify(EntityFilter filter, ModifyChangeDetail changeDetail)
	{
		//CheckModifyAuthorition();

		ManagerActionFactory mgrActionFactory = getManagerActionFactory();
		ModifyByFilterMgrAction multiModifyMgrAction = mgrActionFactory.getModifyByFilterMgrAction(getBEManagerContext(), filter, changeDetail);
		Execute(multiModifyMgrAction);
	}

	@Override
	public final boolean hasChanges(){
		ManagerActionFactory managerActionFactory = getManagerActionFactory();
		HasChangeDetailMgrAction hasChangeDetailMgrAction = managerActionFactory.getHasChangeDetailMgrAction(getBEManagerContext());
		//return hasChangeDetailMgrAction.hasChangeDetail();
		return Execute(hasChangeDetailMgrAction);
	}

    @Override
    public final IEntityData retrieveDefault()
    {
        //CheckCreateAuthorition();

        RetrieveDefaultManagerAction managerAction = getManagerActionFactory().getRetrieveDefaultManagerAction(getBEManagerContext(), false, "", null);
        try {
			BefRetrieveDefaultBroker.fireBeforeRetrieveDefaultManagerAction(getBEManagerContext(),false,"",null);
			IEntityData data=Execute(managerAction);
            BefRetrieveDefaultBroker.fireAfterRetrieveDefaultManagerAction(getBEManagerContext(),data);
            return data;
        }catch (Exception e){
            BefRetrieveDefaultBroker.fireExceptionStop(e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, IEntityData> retrieveDefault(List<String> dataIDs){
        MultiRetrieveDefaultMgrAction managerAction = getManagerActionFactory().getMultiRetrieveDefaultMgrAction(getBEManagerContext(), dataIDs, null);
        return Execute(managerAction);
    }

    @Override
    public final IEntityData retrieveDefault(java.util.Map<String, Object> defaultValues)
    {
        DataValidator.checkForNullReference(defaultValues, "defaultValues");
        RetrieveDefaultManagerAction managerAction = getManagerActionFactory().getRetrieveDefaultManagerAction(getBEManagerContext(), false, "", defaultValues);
        try {
			BefRetrieveDefaultBroker.fireBeforeRetrieveDefaultManagerAction(getBEManagerContext(),false,"",defaultValues);
			IEntityData data=Execute(managerAction);
            BefRetrieveDefaultBroker.fireAfterRetrieveDefaultManagerAction(getBEManagerContext(),data);
            return data;
        }catch (Exception e){
            BefRetrieveDefaultBroker.fireExceptionStop(e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public final IEntityData retrieveDefault(String dataID)
    {
        RetrieveDefaultManagerAction managerAction = getManagerActionFactory().getRetrieveDefaultManagerAction(getBEManagerContext(), true, dataID, null);
        try {
			BefRetrieveDefaultBroker.fireBeforeRetrieveDefaultManagerAction(getBEManagerContext(),true,dataID,null);
			IEntityData data=Execute(managerAction);
            BefRetrieveDefaultBroker.fireAfterRetrieveDefaultManagerAction(getBEManagerContext(),data);
            return data;
        }catch (Exception e){
            BefRetrieveDefaultBroker.fireExceptionStop(e);
            throw new RuntimeException(e);
        }
    }

    public final IEntityData retrieveDefault(String dataID, Map<String, Object> defaultValues)
    {
        RetrieveDefaultManagerAction managerAction = getManagerActionFactory().getRetrieveDefaultManagerAction(getBEManagerContext(), true, dataID, defaultValues);
        try {
			BefRetrieveDefaultBroker.fireBeforeRetrieveDefaultManagerAction(getBEManagerContext(),true,dataID,defaultValues);
			IEntityData data=Execute(managerAction);
            BefRetrieveDefaultBroker.fireAfterRetrieveDefaultManagerAction(getBEManagerContext(),data);
            return data;
        }catch (Exception e){
            BefRetrieveDefaultBroker.fireExceptionStop(e);
            throw new RuntimeException(e);
        }
    }

	@Override
	public final IEntityData clone(String cloneDataID, CloneParameter cloneParameter)
	{
		return clone(cloneDataID, "", cloneParameter);
	}

	@Override
	public final IEntityData clone(String cloneDataID, String dataID, CloneParameter cloneParameter)
	{
		RespectiveRetrieveResult retrieveResult = retrieve(cloneDataID);
		if(retrieveResult == null || retrieveResult.getData() == null){
			throw new RuntimeException("要复制的数据" + cloneDataID + "不存在");
		}
		CloneMgrAction cloneMgrAction = getManagerActionFactory().getCloneMgrAction(getBEManagerContext(), cloneDataID, dataID, cloneParameter);
		return Execute(cloneMgrAction);
	}

	@Override
	public final IEntityData createObjectData()
	{
		return ExecuteNoSession(getManagerActionFactory().getCreateObjectDataMgrAction(this, false, ""));
	}

	private IEntityData createObjectData(String dataID)
	{
		return ExecuteNoSession(getManagerActionFactory().getCreateObjectDataMgrAction(this, true, dataID));
	}

	@Override
	public final IEntityData retrieveDefaultChild(java.util.List<String> nodeCodes, java.util.List<String> hierachyIdList) {
		//CheckCreateAuthorition();
		RetrieveDefaultChildMgrAction managerAction = getManagerActionFactory().getRetrieveDefaultChildManagerAction(getBEManagerContext(), nodeCodes, hierachyIdList, null, null);
		return Execute(managerAction);
	}

	@Override
	public final IEntityData retrieveDefaultChild(java.util.List<String> nodeCodes, java.util.List<String> hierachyIdList, String dataID)
	{
		DataValidator.checkForNullReference(nodeCodes, "nodeCodes");
		DataValidator.checkForNullReference(hierachyIdList, "parentIds");
		DataValidator.checkForEmptyString(dataID, "dataID");
		//CheckCreateAuthorition();

		RetrieveDefaultChildMgrAction managerAction = getManagerActionFactory().getRetrieveDefaultChildManagerAction(getBEManagerContext(), nodeCodes, hierachyIdList, dataID, null);
		return Execute(managerAction);
	}

	public final IEntityData retrieveDefaultChild(java.util.List<String> nodeCodes, java.util.List<String> hierachyIdList, String dataID, Map<String, Object> values)
	{
		RetrieveDefaultChildMgrAction managerAction = getManagerActionFactory().getRetrieveDefaultChildManagerAction(getBEManagerContext(), nodeCodes, hierachyIdList, dataID, values);
		return Execute(managerAction);
	}

	@Override
	public final IEntityData retrieveDefaultChild(java.util.List<String> nodeCodes, java.util.List<String> hierachyIdList, Map<String, Object> values)
	{
		//CheckCreateAuthorition();

		RetrieveDefaultChildMgrAction managerAction = getManagerActionFactory().getRetrieveDefaultChildManagerAction(getBEManagerContext(), nodeCodes, hierachyIdList, null, values);
		return Execute(managerAction);
	}

	@Override
	public final Map<String, IEntityData> retrieveDefaultChild(java.util.List<String> nodeCodes,
		java.util.List<String> hierachyIdList, List<String> dataIDs) {
		MultiRetrieveDefaultChildMgrAction managerAction = getManagerActionFactory()
			.getMultiRetrieveDefaultChildMgrAction(getBEManagerContext(), nodeCodes, hierachyIdList,
				dataIDs);
		return Execute(managerAction);
	}
	@Override
	public  final List<IEntityData> queryWithoutAuthInfo(EntityFilter filter){

		return queryWithoutAuthInfo( "", filter);
    }

	@Override
	public final List<IEntityData> queryWithoutAuthInfo(String nodeCode, EntityFilter filter) {
		try {
			BefQueryEventBroker.fireBeforeQuery(this, filter);
			ManagerActionFactory mgrActionFactory = getManagerActionFactory();
			QueryWithoutAuthInfoMgrAction action = mgrActionFactory.getQueryWithoutAuthInfoMgrAction(getBEManagerContext(), nodeCode, filter);
			List<IEntityData> resultdata = Execute(action);
			BefQueryEventBroker.fireAfterQuery();
			return resultdata;
		} catch (Exception e) {
			BefQueryEventBroker.fireAfterQuery();
			throw new RuntimeException(e);
		}
	}
	@Override
	public final List<IEntityData> query()
	{
		return query(new EntityFilter());
	}

	@Override
	public final List<IEntityData> query(EntityFilter filter)
	{
		//查询权限检查
		//CheckQueryAuthorition();

		return query("", filter);
	}

	@Override
	public final List<IEntityData> query(String nodeCode, EntityFilter filter)
	{
		try {
			BefQueryEventBroker.fireBeforeQuery(this, filter);
			ManagerActionFactory mgrActionFactory = getManagerActionFactory();
			QueryManagerAction queryManagerAction = mgrActionFactory.getQueryMgrAction(getBEManagerContext(), nodeCode, filter);
			List<IEntityData> resultdata = Execute(queryManagerAction);
			BefQueryEventBroker.fireAfterQuery();
			return resultdata;
		}catch(Exception e){
			BefQueryEventBroker.fireAfterQuery();
			throw new RuntimeException(e);
		}
	}


	@Override
	public List<IEntityData> queryWithBuffer(EntityFilter filter) {
		return queryWithBuffer("", filter);
	}

	@Override
	public final List<IEntityData> queryWithBuffer(String nodeCode, EntityFilter filter) {
		try {
			BefQueryEventBroker.fireBeforeQuery(this, filter);
			ManagerActionFactory mgrActionFactory = getManagerActionFactory();
			QueryWithBufferMgrAction queryManagerAction = mgrActionFactory.getQueryWithBufferMgrAction(getBEManagerContext(), nodeCode, filter);
			List<IEntityData> resultdata =Execute(queryManagerAction);
			BefQueryEventBroker.fireAfterQuery();
			return resultdata;
		} catch (Exception e) {
			BefQueryEventBroker.fireAfterQuery();
			throw new RuntimeException(e);
		}
	}


	@Override
	public final void delete(String dataId)
	{
		//CheckDeleteAuthorition();

		DeleteMgrAction mgrAction = getManagerActionFactory().getDeleteMgrAction(getBEManagerContext(), dataId);
		Execute(mgrAction);
	}

	@Override
	public final void delete(java.util.List<String> dataIds)
	{
		//CheckDeleteAuthorition();
		MultiDeleteMgrAction mgrAction = getManagerActionFactory().getMultiDeleteMgrAction(getBEManagerContext(), dataIds);
		Execute(mgrAction);
	}

	@Override
	public final void deleteChild(java.util.List<String> nodeCodes, java.util.List<String> hierachyIdList, java.util.List<String> ids)
	{
		//CheckDeleteChildAuthorition();

		DeleteChildMgrAction mgrAction = getManagerActionFactory().getDeleteChildMgrAction(getBEManagerContext(), nodeCodes, hierachyIdList, ids);
		Execute(mgrAction);
	}

	@Override
	public final String serializeData(IEntityData data)
	{
		return ExecuteNoSession(getManagerActionFactory().getDataSerAction(getBEManagerContext(), data));
	}

	@Override
	public final String serializeDataForExpression(IEntityData data)
	{
	    try {
            SerializerUtil.isKeepAssoPropertyForExpression().set("1");
            return ExecuteNoSession(getManagerActionFactory().getDataSerAction(getBEManagerContext(), data, true));
        }
	    finally {
            SerializerUtil.isKeepAssoPropertyForExpression().remove();
        }
	}

	@Override
	public final IEntityData deSerializeData(String data)
	{
		return ExecuteNoSession(getManagerActionFactory().getDataDeSerAction(getBEManagerContext(), data));
	}

	/**
	 * 子表序列化
	 * @param nodeCodes
	 * @param data
	 * @return
	 */
	@Override
	public final String serializeData(List<String> nodeCodes,IEntityData data){
		throw new UnsupportedOperationException();
	}

	/**
	 * 子表反序列化
	 * @param nodeCodes
	 * @param data
	 * @return
	 */
	@Override
	public final IEntityData deserializeData(List<String> nodeCodes,String data){
		throw new UnsupportedOperationException();
	}
		//region private
	private ManagerActionFactory getManagerActionFactory()
	{
		return new ManagerActionFactory();
	}

		//endregion


		//region 组装器工厂

	protected IMgrActionAssemblerFactory CreateMgrAssemblerFactory() { return null; }

	private IMgrActionAssemblerFactory getNewMgrAssemblerFactory()
	{
		return ((CreateMgrAssemblerFactory()) != null) ? CreateMgrAssemblerFactory() : new MgrActionAssemblerFactory();
	}
		//endregion

	@Override
	public final void clearChangeset()
	{
		ClearChangesetMgrAction mgrAction = getManagerActionFactory().getClearChangesetMgrAction(getBEManagerContext());
		Execute(mgrAction);
	}

	@Override
	public final void clearLock()
	{
		ClearLockMgrAction mgrAction = getManagerActionFactory().getClearLockMgrAction(getBEManagerContext());
		Execute(mgrAction);
	}

	@Override
	public final void clearBuffer()
	{
		ClearBufferMgrAction mgrAction = getManagerActionFactory().getClearBufferMgrAction(getBEManagerContext());
		Execute(mgrAction);
	}

	public final void autoClearBuffer()
	{
		AutoClearBufferMgrAction mgrAction = getManagerActionFactory().getAutoClearBufferMgrAction(getBEManagerContext());
		Execute(mgrAction);
	}

	@Override
	public final IEntityData createData(String dataID)
	{
		return createObjectData(dataID);
	}

	@Override
	public final IEntityData createChildData(String childCode, String dataID)
	{
		return ExecuteNoSession(getManagerActionFactory().getCreateChildDataMgrAction(this, childCode, true, dataID));
	}

	@Override
	public final IEntityData createUnlistenableData(String dataID)
	{
		return ((IBusinessEntity)createSessionlessEntity(dataID)).createEntityData(dataID);
	}

	@Override
	public final IEntityData createUnlistenableChildData(String childCode, String dataID)
	{
IAccessor acs = (IAccessor)((IBusinessEntity)createSessionlessEntity(dataID)).createChildData(childCode, dataID);
		return (IEntityData)acs.getInnerData();
	}

	@Override
	public final IEntityData deserializeData(String serializedData)
	{
		return deSerializeData(serializedData);
	}

	HashMap<String, ArrayList<UQConstraintConfig>> uqConstraintConfigs;

	@Override
	public java.util.HashMap<String, java.util.ArrayList<UQConstraintConfig>> getConstraintInfo() { return uqConstraintConfigs; }

	@Override
	public void setConstraintInfo(HashMap<String, ArrayList<UQConstraintConfig>> uqConstraintConfigs) {
		if(this.uqConstraintConfigs == null){
			this.uqConstraintConfigs = uqConstraintConfigs;
		}
		else {
			this.uqConstraintConfigs.putAll(uqConstraintConfigs);
		}
	}

	protected abstract AbstractCefChangeSerializer getChangeSerializer();

	protected abstract AbstractCefChangeJsonDeserializer getChangeDeserializer();


	public abstract AbstractBizEntitySerializer getDataSerialize();
	public abstract AbstractBizEntityDeSerializer getDataDeserizlier() ;
	@Override
	public final String serializeChanges(java.util.List<IChangeDetail> changes) {
		try {
			return getChangeJsonMapper(false).writeValueAsString(changes);
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
	}

	public final String serializeChanges(java.util.List<IChangeDetail> changes,boolean isUseStdTime){
		try {
			return getChangeJsonMapper(isUseStdTime).writeValueAsString(changes);
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
	}
	private ObjectMapper getChangeJsonMapper(boolean isUseStdTime) {
		ObjectMapper mapper = new ObjectMapper();
		SimpleModule module = new SimpleModule();
		List<IBEEntityExtend> entityExtList = (extList != null ? extList : Collections.emptyList()).stream()
			.map(item -> ((IBEManagerExtend)item).getDataTypeExtend()).filter(item -> item != null).collect(
				Collectors.toList());

		AbstractCefChangeSerializer changeSerializer = getChangeSerializer();
		CefSerializeContext context = new CefSerializeContext();
		context.setEnableStdTimeFormat(isUseStdTime);
		changeSerializer.setCefSerializeContext(context);
		module.addSerializer(IChangeDetail.class, changeSerializer);
		entityExtList.forEach(item -> changeSerializer.addExtend(item));

		AbstractCefChangeJsonDeserializer changeDeserializer = getChangeDeserializer();
		module.addDeserializer(IChangeDetail.class, changeDeserializer);
		changeDeserializer.setCefSerializeContext(context);
		entityExtList.forEach(item -> changeDeserializer.addExtend(item));

		mapper.registerModule(module);
		return mapper;
	}

	public  ObjectMapper getDataJsonMapper() {
		SimpleModule module = new SimpleModule();
		List<IBEEntityExtend> entityExtList = (extList != null ? extList : Collections.emptyList()).stream()
			.map(item -> ((IBEManagerExtend) item).getDataTypeExtend()).filter(item -> item != null)
			.collect(Collectors.toList());

		AbstractBizEntitySerializer serializer = getDataSerialize();
		module.addSerializer(ICefData.class, serializer);
		entityExtList.forEach(item -> serializer.addExtend(item));

		AbstractBizEntityDeSerializer deserializer = getDataDeserizlier();
		deserializer.setManger(this);
		module.addDeserializer(ICefData.class, deserializer);
		entityExtList.forEach(item -> deserializer.addExtend(item));


		ObjectMapper mapper = new ObjectMapper(){{registerModule(module);}};
		return mapper;
	}

	public final  ObjectMapper getDataJsonMapperKeepAssoPropertyForExpr()
	{
		SimpleModule module = new SimpleModule();
		List<IBEEntityExtend> entityExtList = (extList != null ? extList : Collections.emptyList()).stream()
				.map(item -> ((IBEManagerExtend) item).getDataTypeExtend()).filter(item -> item != null)
				.collect(Collectors.toList());

		AbstractBizEntitySerializer serializer = getDataSerialize();
		module.addSerializer(ICefData.class, serializer);
		entityExtList.forEach(item -> serializer.addExtend(item));
		CefSerializeContext cefSerializeContext=CefSerializeContext.getSerContextKeepAssoPropertyForExpression();
		serializer.setCefSerializeContext(cefSerializeContext);

		AbstractBizEntityDeSerializer deserializer = getDataDeserizlier();
		deserializer.setManger(this);
		module.addDeserializer(ICefData.class, deserializer);
		entityExtList.forEach(item -> deserializer.addExtend(item));


		ObjectMapper mapper = new ObjectMapper(){{registerModule(module);}};
		return mapper;
	}

	@Override
	public String serializeChange(IChangeDetail change)
	{
		try {
			return getChangeJsonMapper(false).writeValueAsString(change);
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public IChangeDetail deserializeChange(String changeStr){
		try {
			return getChangeJsonMapper(false).readValue(changeStr, IChangeDetail.class);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public final java.util.ArrayList<IChangeDetail> deserializeChanges(String strChanges)
	{
		try {
			ObjectMapper  mapper = getChangeJsonMapper(false);
			JavaType type = mapper.getTypeFactory().
					constructCollectionType(ArrayList.class, IChangeDetail.class);
			return mapper.readValue(strChanges, type);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	public final java.util.ArrayList<IChangeDetail> deserializeChanges(String strChanges,boolean isUseStdTime)
	{
		try {
			ObjectMapper  mapper = getChangeJsonMapper(isUseStdTime);
			JavaType type = mapper.getTypeFactory().
					constructCollectionType(ArrayList.class, IChangeDetail.class);
			return mapper.readValue(strChanges, type);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public final void generateTable(String nodeCode)
	{
		getRepository().generateTable(nodeCode);
	}

	@Override
	public final void dropTable(String nodeCode)
	{
		getRepository().dropTable(nodeCode);
	}

//ORIGINAL LINE: public bool isReferred(string befConfig, string dataId, string nodeCode = "")
	@Override
	public final boolean isReferred(String befConfig, String dataId, String nodeCode)
	{
		//Java版临时注释 删除检查优先级低
		return false;
//		if (DotNetToJavaStringHelper.isNullOrEmpty(nodeCode))
//		{
//			nodeCode = "RootNode";
//		}
//		var service = ServiceManager.<IReferenceCheckService>GetService();
//		String dbCode = befConfig + "/" + nodeCode;
//		var result = service.checkReference(dbCode, dataId);
//		return result.Referenced;
	}

	@Override
	public final boolean isEffective(String nodeCode, String dataId)
	{
		IsEffectiveMgrAction mgrAction = getManagerActionFactory().getIsEffectiveMgrAction(getBEManagerContext(), nodeCode, dataId);
		return Execute(mgrAction);
	}

	public final  boolean isDatasEffective(String nodeCode,List<String> dataIDs, RefObject<List<String>> noneEffectiveDatas)
	{
		MultiEffectiveMgrAction action =getManagerActionFactory().getMultiEffectiveMgrAction(getBEManagerContext(),nodeCode,dataIDs);
		MultiEffectiveResult reuslt =  Execute(action);
		noneEffectiveDatas.argvalue=reuslt.getNoneEffectiveDatas();
		return reuslt.isEffectResult();
	}

	public final  boolean isDatasEffective(String nodeCode, String propName, List<String> dataIDs, RefObject<List<String>> noneEffectiveDatas)
	{
		MultiEffectiveMgrAction action =getManagerActionFactory().getMultiEffectiveMgrAction(getBEManagerContext(),nodeCode,dataIDs, propName);
		MultiEffectiveResult reuslt =  Execute(action);
		noneEffectiveDatas.argvalue=reuslt.getNoneEffectiveDatas();
		return reuslt.isEffectResult();
	}

   private SaveEventBroker saveEventBroker;
	private SaveEventBroker getSaveEventBroker(){
		if(saveEventBroker == null){
			saveEventBroker= SpringBeanUtils.getBean(SaveEventBroker.class);
		}
		return saveEventBroker;
	}

	public void fireAfterSave() {
		getSaveEventBroker().init();
		getSaveEventBroker().fireAfterSave(this);
	}

	public void fireBeforeSave() {
		getSaveEventBroker().init();
		getSaveEventBroker().fireBeforeSave(this);
	}

	public IEntityRTDtmAssembler getBeforeQueryDtmAssembler() {
		IEntityRTDtmAssembler assembler = createBeforeQueryDtmAssembler();
		if(assembler != null && assembler instanceof BefB4QueryDtmAssembler) {
			addBeforeQueryDtm((BefB4QueryDtmAssembler)assembler);
		}
		return assembler;
	}

	protected void addBeforeQueryDtm(BefB4QueryDtmAssembler assembler){
	}

	public  IEntityRTDtmAssembler getBeforeRetrieveDtmAssembler() {
		IEntityRTDtmAssembler assembler = createBeforeRetrieveDtmAssembler();
		if(assembler != null && assembler instanceof BefBeforeRetrieveDtmAssembler) {
			addBeforeRetrieveDtm((BefBeforeRetrieveDtmAssembler)assembler);
		}
		return assembler;
	}

	protected void addBeforeRetrieveDtm(BefBeforeRetrieveDtmAssembler assembler){}

	protected IEntityRTDtmAssembler createBeforeRetrieveDtmAssembler() {
		return new BefBeforeRetrieveDtmAssembler();
	}

	protected IEntityRTDtmAssembler createBeforeQueryDtmAssembler() { return new BefB4QueryDtmAssembler(); }

	/**
	 国际化资源-模型

	 @return
	*/
	public ModelResourceInfos getModelResourceInfos()
	{
		return null;
	}
	@Override
	public ModelResInfo getModelInfo()
	{
		return null;
	}

	/**
	 国际化资源-主实体

	*/
	public final EntityResInfo getRootEntityResInfo() {
		ModelResInfo modelReourceInfo = getModelInfo();
		return modelReourceInfo != null
				? modelReourceInfo.getCustomResource(modelReourceInfo.getRootNodeCode()) : null;
	}


		//region CefRootManager override
	@Override
	protected IRootManagerContext createRootManagerContext()
	{
		BEManagerContext result  =new BEManagerContext(getNewMgrAssemblerFactory());
		result.setExtend(extList);
		return result;
	}

  public IBeBufferChangeManager getBufferChangeManager() {
		return getSessionItem().getBufferChangeManager();
  }

  @Override
  protected final IChangesetManager createChangesetManager() {
    return getBufferChangeManager();
  }

  @Override
  protected final IBufferManager createBufferManager() {
    return getBufferChangeManager();
  }

	@Override
	protected IRootEntityCacheManager createEntityCacheManager() {return getBEManagerContext().getCacheManager();}

	@Override
	public ICefData deserialize(String content) {return deSerializeData(content);}

	@Override
	public String serialize(ICefData data){return serializeData((IEntityData)data);}

	@Override
	public IRootRepository getRepository() {
		IRootRepository repository = getRepositoryFactory().createRepository(this.getBEType());
		FuncSession currentSession = getBEManagerContext().getSession();
		repository.initParams(currentSession.getBefContext().getParams());
		repository.initRepoVariables(
				currentSession.getFuncSessionItem(this.getBEType()).getRepositoryVariables());
		return repository;
	}

	protected IRepositoryFactory getRepositoryFactory(){
  	return BefRtBeanUtil.getBefRepositoryFactory();
	}

  public BEFuncSessionBase getSessionItem() {
		return getBEManagerContext().getSessionItem();
  }

	//endregion


		//region BizEntity
	@Override
	protected ICefEntityContext createEntityContext()
	{
		CoreBEContext tempVar = new CoreBEContext();
		tempVar.setResponse(getResponseContext());
		tempVar.setBEManagerContext(getBEManagerContext());
		return tempVar;
			//DtmAssemblerFactory = CreateDtmAssemblerFactory(),
			//ValidationAssemblerFactory = CreateValidationAssemblerFactory()
	}

	@Override
	public void customInitEntityContext(ICefEntityContext context) {
		super.customInitEntityContext(context);
		CoreBEContext beContext = (CoreBEContext)context;
		if (extList != null) {
			((BusinessEntity)((CoreBEContext) context).getBizEntity()).setExtend(
					extList.stream().map(item -> item.getDataTypeExtend()).filter(item -> item != null)
							.collect(Collectors.toList()));
		}
		beContext.setAccessorCreator(getAccessorCreator());
		beContext.setResponse(getResponseContext());
		//Java版临时注释 变量优先级低
		beContext.setVarBufferManager( getBEManagerContext().getVarBufferManager());
		beContext.setSessionItem(getSessionItem());
		beContext.setCode(((BusinessEntity)beContext.getDataType()).getNodeCode());
		beContext.setModelResInfo(getModelInfo());
		//执行不需要session的动作时BufferManager为null
		if (getBufferChangeManager() != null)
		{
			beContext.setCurrentData(getBufferChangeManager().getCurrentData(beContext.getID()));
			beContext.setTransactionData(getBufferChangeManager().getTransactionData(beContext.getID()));
			beContext.setOriginalData(getBufferChangeManager().getOriginalData(beContext.getID()));
		}
	}

	@Override
	protected void customInitSessionlessEntityContext(ICefEntityContext context) {
		super.customInitEntityContext(context);
		CoreBEContext beContext = (CoreBEContext)context;
		if (extList != null) {
			((BusinessEntity)((CoreBEContext) context).getBizEntity()).setExtend(
					extList.stream().map(item -> item.getDataTypeExtend()).filter(item -> item != null)
							.collect(Collectors.toList()));
		}
		beContext.setAccessorCreator(getAccessorCreator());
		beContext.setResponse (getResponseContext());
	}

	@Override
	protected final ICefRootEntity newEntity(String id) {
		IBusinessEntity bizEntity = createBusinessEntity(id);
		((BusinessEntity)bizEntity).setBEType(getBEType());
		return bizEntity;
	}

	@Override
	public final IBusinessEntity getEntity(String id) {
		IBusinessEntity result =  (IBusinessEntity)super.getEntity(id);
		((BEContext)result.getBEContext()).setSessionItem(getSessionItem());
		return result;
	}

	protected abstract IBusinessEntity createBusinessEntity(String id);

		//endregion

		//region ExecuteAction
	protected final <TResult> TResult Execute(AbstractManagerAction<TResult> action)
	{
		DataValidator.checkForNullReference(action, "com/inspur/edp/bef/core/action");
		BEMgrActionExecutor<TResult> executor = (BEMgrActionExecutor<TResult>)getBEManagerContext().getActionExecutor();
		executor.setAction(action);
		return executor.execute();
	}

	protected final <TResult> TResult ExecuteNoSession(AbstractManagerAction<TResult> action)
	{
		DataValidator.checkForNullReference(action, "action");
		action.setBEManagerContext(getBEManagerContext());
		((ICefMgrAction<TResult>)action).execute();
		return action.getResult();
	}

		//endregion


		//region 变更集状态控制, 仅框架内部使用
	public final void clearCurrentChanges()
	{
		List<IBusinessEntity> allBes = getBEManagerContext().getAllEntities();
		if (allBes == null)
		{
			return;
		}
for (IBusinessEntity be : allBes)
		{
			IChangeDetail currentChange = be.getBEContext().getCurrentChange();
			if(currentChange != null && currentChange instanceof AddChangeDetail)
					removeEntity(be.getID());
			else
			// if (!com.inspur.edp.bef.core.be.BEContext.hasData()) continue;
				((CoreBEContext)be.getBEContext()).rejectChanges();
		}
	}

	public final void mergeCurrentDataToTransaction()
	{
		getBEManagerContext().consumeAllEntites(be -> {
			if (be.getBEContext().hasData()) {
				((CoreBEContext) be.getBEContext()).acceptChanges();
			}
		});
	}

	public final void mergeTransactionDataToOriginal()
	{
		getBEManagerContext().consumeAllEntites(be -> {
			if (be.getBEContext().hasData()) {
				IChangeDetail tchange = be.getBEContext().getTransactionalChange();
				boolean removed = tchange != null && tchange.getChangeType() == ChangeType.Deleted;
				((CoreBEContext) be.getBEContext()).acceptTransaction();
				if(removed)
					removeEntity(be.getID());
			}
		});
	}

	//TODO: [add] 搞一个ManagerAction
	/**
	 循环所有entity对新产生的entity或已有的entity产生了新修改的, 执行保存前联动计算

	 @return 是否有entity执行了联动计算
	*/
	public final boolean beforeSaveDeterminate() {
		boolean anySaved = false;
		for (ICefRootEntity entityInterface : getBEManagerContext().getCacheManager().getAllEntities()) {
			BusinessEntity entity =(BusinessEntity)entityInterface;
			setVersionControlInfo(entity);
			if (entity.getBEContext().getBeforeSaveDeterminated()) {//已有的Entity
				anySaved |= entity.additionalBeforeSaveDeterminate();
			} else {//新产生的Entity
				entity.beforeSaveDeterminate();
				anySaved = true;
			}
		}
		return anySaved;
	}

  public final void onCancelDeterminate() {
		getBEManagerContext().consumeAllEntites(entity -> {
      ((BusinessEntity) entity).onCancelDeterminate();
    });
  }

	public final void onAfterSaveValidate(String id, DataSaveResult saveResult) {
		((BusinessEntity) getEntity(id)).afterSaveValidate(saveResult);
	}

	private void setVersionControlInfo(BusinessEntity entity){
		if(entity.getBEContext().isDeleted() || entity.getContext().getData()==null){
			return;
		}
		entity.setVersionControlPropValue(new Date());
	}

	public final void clearB4SaveDtmFlag() {
		getBEManagerContext().consumeAllEntites(entity -> {
			((CoreBEContext)entity.getBEContext()).setBeforeSaveDeterminated(false);
			((CoreBEContext)entity.getBEContext()).setVersionSetted(false);
		});
	}

	public final void beforeSaveCodeGenerate(SaveContext ctx)
	{
		getBEManagerContext().consumeAllEntites(entity -> {
			((BusinessEntity)entity).beforeSaveCodeGenerate(ctx);
		});
	}

	public final void beforeSaveValidate() {
		getBEManagerContext().consumeAllEntites(entity -> entity.beforeSaveValidate());
	}

	public final void saveWithScope()
	{
		getBEManagerContext().consumeAllEntites(entity -> {
			CoreBEContext beContext = ((BusinessEntity) entity).getBEContext();
			beContext.mergeIntoInnerChange();
			beContext.acceptListenerChange();
			beContext.acceptTempChange();
			((BusinessEntity)entity).saveWithScope();
		});
	}

		//endregion

	protected  IVariableManager createVariableManager(){return null;}

	public IVariableManager internalCreateVariableManager(){return createVariableManager();}

	@Override
	public final void modifyVariable(IChangeDetail change)
	{
		VariableModifyMgrAction action = getManagerActionFactory().getVariableModifyMgrAction(getBEManagerContext(), change);
		Execute(action);
	}


	public IVariableData getVariables(){return getBEManagerContext().getVariables();}

	public IVariableData getReadonlyVariables(){return getBEManagerContext().getReadonlyVariables();}

	@Override
	public final void setRepositoryVariable(String key, String value)
	{
		getBEManagerContext().getRepoVariables().put(key, value);
	}

	public void removeEntity(String entityID)
	{
		//businessEntity与change和buffer分开存储, 需要分别删除
		getBEManagerContext().getCacheManager().deleteEntity(entityID);
		getBufferChangeManager().remove(entityID);
	}

	@Override
	public List<String> getDistinctFJM(String fjnPropertyName, EntityFilter filter, Integer parentLayer) {
		return getRepository().getDistinctFJM(fjnPropertyName,filter,QueryManagerAction.getAuthorityInfos(getBEManagerContext()),parentLayer);
	}

	//region [运行时对定制]扩展
	private List<IBEManagerExtend> extList;

	public final void setExtends(List<IBEManagerExtend> extList) {
		this.extList = extList;
	}

	public void setLcpParam(StandardLcpParam param) {
		this.lcpParam = param;
	}
  public StandardLcpParam getLcpParam() {
    return this.lcpParam;
  }

	public DataSaveParameter getDataSavePar(String id) {
		IBusinessEntity entity = getEntity(id);
		return entity == null ? null : ((CoreBEContext) entity.getBEContext()).getDataSavePar();
	}

	@Override
	public Object executeCustomAction(String actionCode, Object... pars){
		RefObject<Object> result = new RefObject<>(new Object());
		for (IBEManagerExtend extendItem : extList){
			extendItem.setLcpParam(lcpParam);
			boolean hasExecute = extendItem.invokeAction(actionCode, result, getBEManagerContext(), pars);
			if(hasExecute)
				return result.argvalue;
		}
		throw new RuntimeException("找不到动作" + actionCode);
//		throw new RuntimeException("生成型工程不支持 executeCustomAction");
	}
//endregion

	//region 全量接口
	@Override
	public IEntityData retrieveDefault(IEntityData data) {
		Objects.requireNonNull(data, "data");

		FullRetrieveDefaultMgrAction action = new FullRetrieveDefaultMgrAction(this, data);
		Execute(action);
		return action.getResult();
	}

	@Override
	public void modify(IEntityData data) {
		Objects.requireNonNull(data, "data");

		Execute(new FullModifyMgrAction(this, data));
	}

	@Override
	public BefTempTableContext createTempTable(List<String> nodeCodes) {
		CreateTempTableMgrAction action=new CreateTempTableMgrAction(nodeCodes);
		Execute(action);
		return action.getResult();
	}

	@Override
	public void dropTempTable(BefTempTableContext tempTableContext) {
		DropTempTableMgrAction dropTempTableMgrAction=new DropTempTableMgrAction(tempTableContext);
		Execute(dropTempTableMgrAction);
	}

	public Object createPropertyDefaultValue(String nodeCode,String propertyName) {
		throw new UnsupportedOperationException();
	}
	//endregion

	//region tcc
	public void checkSupportTcc() {
		if(getModelInfo() != null && ((BefModelResInfoImpl)getModelInfo()).getTccSupported())
			return ;
		getBEManagerContext().consumeAllEntites(be -> {
			if (((CoreBEContext)be.getBEContext()).hasChange()) {
				throw new BefEngineException(ErrorCodes.UnsupportedInTcc, "业务实体[" + getBEType() +"]不支持在Tcc分布式事务中进行数据修改", null);
			}
		});
	}

	public void tccCancel(BusinessActionContext tccContext, BefTccParamItem item)
			throws SQLException {
		new MgrTccCancelAction(getBEManagerContext(), tccContext, item).execute();
	}

	public void tccConfirm(BusinessActionContext tccContext, BefTccParamItem item)
			throws SQLException {
		new MgrTccConfirmAction(getBEManagerContext(),tccContext, item).execute();
	}

	public BefTccParamItem buildTccParam() {
		List<IChangeDetail> changes = new ArrayList<>();
		getBEManagerContext().consumeAllEntites(item -> {
			if(!((BEContext)item.getBEContext()).hasChange())
				return;
			changes.add(((BusinessEntity)item).buildReverseTranChanges());
		});
		if(changes.isEmpty())
			return null;

		BefModelResInfoImpl modelInfo = (BefModelResInfoImpl) getModelInfo();
		BefTccParamItem item = new BefTccParamItem(){{
			setConfigId(getBEType());
			setChanges(changes);
			setChangesStr(serializeChanges(changes));
		}};
		if(modelInfo.getAutoTccLock()) {
			String lock = LockService.getInstance().upgradeLock4Tcc(getBEType());
			item.setLockId(lock);
		}
		return item;
	}

//	public void reverse4SaveFailed(List<IChangeDetail> changes) {
//		if(changes.isEmpty())
//			return;
//		for(IChangeDetail change : changes) {
//		 BusinessEntity entity = (BusinessEntity) getEntity(change.getDataID());
//		 entity.reverse4SaveFailed(change);
//		}
//	}

	public List<IChangeDetail> buildReverseTranChanges(){
  	List<IChangeDetail> rez = new ArrayList<>();
		getBEManagerContext().consumeAllEntites(item -> {
			IChangeDetail reverseChange = ((BusinessEntity)item).buildReverseTranChanges();
			if(reverseChange != null)
				rez.add(reverseChange);
		});
		return rez;
	}
	//endregion



	@Override
	public Object generateDataId(String nodeCode) {
		EntityResInfo resInfo= getModelInfo().getCustomResource(nodeCode);
		if(resInfo == null || !(resInfo instanceof BefEntityResInfoImpl))
			return UUID.randomUUID().toString();
		ColumnGenerateInfo columnGenerateInfo=((BefEntityResInfoImpl)resInfo).getColumnGenerateInfo();
		return ColumnGenerateConfigLoader.getId(columnGenerateInfo);
	}
}
